package com.aiyun.websocket.tiowebsocketdemo.service;

import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.http.common.HttpRequest;
import org.tio.http.common.HttpResponse;
import org.tio.websocket.common.WsRequest;
import org.tio.websocket.server.handler.IWsMsgHandler;

import org.springframework.stereotype.Component;

/**
 * 处理websocket消息
 */
@Component
public class TioWsMsgHandler implements IWsMsgHandler {
	@Override
	public HttpResponse handshake(HttpRequest httpRequest, HttpResponse httpResponse, ChannelContext channelContext) throws Exception {
		System.out.println("握手");
		String token = httpRequest.getParam("token");
		String user = httpRequest.getParam("user");
		if (token != null && user != null) {
			System.out.println("存在用户和令牌，握手通过");
			Tio.bindUser(channelContext, user);
			return httpResponse;
		}
		return null;
	}

	@Override
	public void onAfterHandshaked(HttpRequest httpRequest, HttpResponse httpResponse, ChannelContext channelContext) throws Exception {
		System.out.println("握手完成");
	}

	@Override
	public Object onBytes(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) throws Exception {
		return null;
	}

	@Override
	public Object onClose(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) throws Exception {
		return null;
	}

	@Override
	public Object onText(WsRequest wsRequest, String s, ChannelContext channelContext) throws Exception {
		System.out.println("收到客户端信息，内容是:" + s);
		return "收到消息";
	}
}
